module mod_elgdata
use mod_elglike_element
use mod_elglike_element

implicit none

 type, public :: t_elgdata
     integer :: lmax
     type(t_elglike_element), dimension(:), allocatable :: elements
  end type t_elgdata




type(t_elgdata) :: global_elgdata

integer :: global_lmax = 1000
integer :: global_lmax_data = 1000

integer :: global_steps = 2

integer :: global_l_step = 20

integer :: global_ierr, global_num_procs, global_my_id

integer :: global_id_master = 0

integer :: global_tag = 100


contains

subroutine elgdata_initialize(elgdata, lmax)
    implicit none
    type(t_elgdata), intent(inout) :: elgdata

    integer, intent(in) :: lmax

    integer :: i
    if (allocated(elgdata%elements) .and. (elgdata%lmax .ne. lmax)) deallocate(elgdata%elements)
    elgdata%lmax = lmax
    if (.not. allocated(elgdata%elements))  allocate(elgdata%elements(lmax))

    do i=1, lmax
       call elglike_element_initialize(elgdata%elements(i))
    end do

  end subroutine elgdata_initialize


subroutine elgdata_save(elg, filename) 
  character(len=*), intent(in) :: filename
  type(t_elgdata), intent(in) :: elg

  integer :: filehandle,i,j,k

  filehandle = 12
  write(*,*) "Saving zbins = ", zbins
  open(unit=filehandle,file=filename,action='write',form='unformatted')
  write(filehandle), elg%lmax
  write(filehandle), zbins
  do i=1, elg%lmax
     write(filehandle), elg%elements(i)%array%val
     write(filehandle), elg%elements(i)%determinant
  end do
    
  close(filehandle)


end subroutine elgdata_save

subroutine elgdata_load(elg, filename) 
  character(len=*), intent(in) :: filename
  type(t_elgdata), intent(inout) :: elg

  integer :: filehandle, i, zb

  filehandle = 12
    
  open(unit=filehandle,file=filename,action='read',form='unformatted')
  read(filehandle), elg%lmax
  read(filehandle), zb
  if (zb .ne. zbins) then
     write(*,*) "Fatal error: datafile has zbins=",zb," and not ",zbins,", as required"
     stop
  end if
  write(*,*) "Loading data lmax " , elg%lmax, " with zbins", zb
  allocate(elg%elements(elg%lmax))
  do i=1, elg%lmax
     call elglike_element_initialize(elg%elements(i))
     read(filehandle), elg%elements(i)%array%val
     read(filehandle), elg%elements(i)%determinant
  end do

  close(filehandle)

end subroutine elgdata_load





end module mod_elgdata
